package jnpf.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.UserInfo;
import jnpf.config.PermissionsConfig;
import jnpf.entity.*;
import jnpf.mapper.ZXGL_RenWuFanKuiMapper;
import jnpf.model.zxgl_renwufankui.ZXGL_RenWuFanKuiPagination;
import jnpf.permission.service.AuthorizeService;
import jnpf.service.*;
import jnpf.util.DateUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * ZXGL_RenWuFanKui
 * 版本： V2.0
 * 版权： 河北交投智能交通技术有限责任公司
 * 作者： 数字交投项目组
 * 日期： 2025-03-21
 */
@Service
public class ZXGL_RenWuFanKuiServiceImpl extends ServiceImpl<ZXGL_RenWuFanKuiMapper, ZXGL_RenWuFanKuiEntity> implements ZXGL_RenWuFanKuiService {
    private static final Logger logger = LoggerFactory.getLogger(ZXGL_RenWuFanKuiServiceImpl.class);

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private AuthorizeService authorizeService;

    @Autowired
    private ZXGL_RenWuFanKuiJiaoFuWuService zXGL_RenWuFanKuiJiaoFuWuService;

    @Autowired
    private ZXGL_XieBanRenWuFanKuiMXService zXGL_XieBanRenWuFanKuiMXService;

    @Autowired
    private ZXGL_XiangMuFenJie_mingxibiaoService zxglXiangMuFenJieMingxibiaoService;

    @Autowired
    private ZXGL_XiangMuLiXiang_MingXiService zxgl_xiangMuLiXiang_mingXiService;
    @Resource
    PermissionsConfig permissionsConfig;

    @Override
    public List<ZXGL_RenWuFanKuiEntity> getList(ZXGL_RenWuFanKuiPagination zXGL_RenWuFanKuiPagination) {

        List<String> AllIdList = new ArrayList();
        int total = 0;
        QueryWrapper<ZXGL_RenWuFanKuiEntity> zXGL_RenWuFanKuiQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ZXGL_XieBanRenWuFanKuiMXEntity> zXGL_XieBanRenWuFanKuiMXQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ZXGL_RenWuFanKuiJiaoFuWuEntity> zXGL_RenWuFanKuiJiaoFuWuQueryWrapper = new QueryWrapper<>();
        //TODO 增加权限逻辑
        UserInfo userInfo = userProvider.get();
        if (!userInfo.getIsAdministrator()) {
            String alldataRoleId = permissionsConfig.getAlldataRoleid();
            List<String> roleIds = userInfo.getRoleIds();
            if (roleIds == null || (StringUtils.isNotBlank(alldataRoleId) && !roleIds.contains(alldataRoleId))) {
                String userId = userInfo.getUserId();
                //任务反馈：创建人看本人数据；主责部门负责人看本部门数据；主责部门主管领导看所管理部门数据；
                zXGL_RenWuFanKuiQueryWrapper.lambda().and(wrapper -> wrapper
                        .eq(ZXGL_RenWuFanKuiEntity::getDepartmentManagerZzbm, userId)//主责部门负责人看本部门数据
                        .or()
                        .eq(ZXGL_RenWuFanKuiEntity::getDepartmentHeadleaderZzbm, userId) //主责部门主管领导看所管理部门数据
                        .or()
                        .eq(ZXGL_RenWuFanKuiEntity::getCreatorUserId, userId)//创建人看本人数据
                );

            }
        }
        int zXGL_RenWuFanKuiNum = 0;
        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getFkr())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getFkr, zXGL_RenWuFanKuiPagination.getFkr());
        }

        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getFkbm())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getFkbm, zXGL_RenWuFanKuiPagination.getFkbm());
        }
        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getRwmc())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().like(ZXGL_RenWuFanKuiEntity::getRwmc, zXGL_RenWuFanKuiPagination.getRwmc());
        }

        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getFkrq())) {
            zXGL_RenWuFanKuiNum++;
            List<String> FkrqList = zXGL_RenWuFanKuiPagination.getFkrq();
            Long fir = Long.valueOf(FkrqList.get(0));
            Long sec = Long.valueOf(FkrqList.get(1));

            zXGL_RenWuFanKuiQueryWrapper.lambda().ge(ZXGL_RenWuFanKuiEntity::getFkrq, new Date(fir))
                    .le(ZXGL_RenWuFanKuiEntity::getFkrq, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

        }

        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getSsxm())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().like(ZXGL_RenWuFanKuiEntity::getSsxm, zXGL_RenWuFanKuiPagination.getSsxm());
        }

        if (AllIdList.size() > 0) {
            zXGL_RenWuFanKuiQueryWrapper.lambda().in(ZXGL_RenWuFanKuiEntity::getId, AllIdList);
        }
        /**
         * 数据权限 此处手动写入菜单id
         */
//        String moduleId = "672468541835867781";
//        if (!userProvider.get().getIsAdministrator()) {
//            Object conditionObj = authorizeService.getCondition(zXGL_RenWuFanKuiQueryWrapper, userProvider.get(), moduleId);
//            if (ObjectUtil.isEmpty(conditionObj)) {
//                return new ArrayList<>();
//            }
//            zXGL_RenWuFanKuiQueryWrapper = (QueryWrapper<ZXGL_RenWuFanKuiEntity>) authorizeService.getCondition(zXGL_RenWuFanKuiQueryWrapper, userProvider.get(), moduleId);
//        }
        //排序
//        if (StringUtil.isEmpty(zXGL_RenWuFanKuiPagination.getSidx())) {
//            zXGL_RenWuFanKuiQueryWrapper.lambda().orderByDesc(ZXGL_RenWuFanKuiEntity::getSsxm);
//        } else {
//            try {
//                String sidx = zXGL_RenWuFanKuiPagination.getSidx();
//                logger.info("sidx===================>" + sidx);
//                ZXGL_RenWuFanKuiEntity zXGL_RenWuFanKuiEntity = new ZXGL_RenWuFanKuiEntity();
//                if (StringUtil.isNotEmpty(sidx)) {
//                    Field declaredField = zXGL_RenWuFanKuiEntity.getClass().getDeclaredField(sidx);
//                    declaredField.setAccessible(true);
//                    String value = declaredField.getAnnotation(TableField.class).value();
//                    zXGL_RenWuFanKuiQueryWrapper = "asc".equals(zXGL_RenWuFanKuiPagination.getSort().toLowerCase()) ? zXGL_RenWuFanKuiQueryWrapper.orderByAsc(value) : zXGL_RenWuFanKuiQueryWrapper.orderByDesc(value);
//                }
//            } catch (NoSuchFieldException e) {
//                e.printStackTrace();
//            }
//        }
        zXGL_RenWuFanKuiQueryWrapper.lambda().orderByDesc(ZXGL_RenWuFanKuiEntity::getCreatorTime);
        if ((total > 0 && AllIdList.size() > 0) || total == 0) {
            Page<ZXGL_RenWuFanKuiEntity> page = new Page<>(zXGL_RenWuFanKuiPagination.getCurrentPage(), zXGL_RenWuFanKuiPagination.getPageSize());
            IPage<ZXGL_RenWuFanKuiEntity> userIPage = this.page(page, zXGL_RenWuFanKuiQueryWrapper);
            return zXGL_RenWuFanKuiPagination.setData(userIPage.getRecords(), userIPage.getTotal());
        } else {
            List<ZXGL_RenWuFanKuiEntity> list = new ArrayList();
            return zXGL_RenWuFanKuiPagination.setData(list, list.size());
        }
    }

    @Override
    public List<ZXGL_RenWuFanKuiEntity> getTypeList(ZXGL_RenWuFanKuiPagination zXGL_RenWuFanKuiPagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        int total = 0;
        QueryWrapper<ZXGL_RenWuFanKuiEntity> zXGL_RenWuFanKuiQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ZXGL_XieBanRenWuFanKuiMXEntity> zXGL_XieBanRenWuFanKuiMXQueryWrapper = new QueryWrapper<>();
        QueryWrapper<ZXGL_RenWuFanKuiJiaoFuWuEntity> zXGL_RenWuFanKuiJiaoFuWuQueryWrapper = new QueryWrapper<>();
        int zXGL_RenWuFanKuiNum = 0;
        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getFkr())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getFkr, zXGL_RenWuFanKuiPagination.getFkr());
        }

        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getFkbm())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getFkbm, zXGL_RenWuFanKuiPagination.getFkbm());
        }

        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getFkrq())) {
            zXGL_RenWuFanKuiNum++;
            List<String> FkrqList = zXGL_RenWuFanKuiPagination.getFkrq();
            Long fir = Long.valueOf(FkrqList.get(0));
            Long sec = Long.valueOf(FkrqList.get(1));

            zXGL_RenWuFanKuiQueryWrapper.lambda().ge(ZXGL_RenWuFanKuiEntity::getFkrq, new Date(fir))
                    .le(ZXGL_RenWuFanKuiEntity::getFkrq, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));

        }

        if (StringUtil.isNotEmpty(zXGL_RenWuFanKuiPagination.getSsxm())) {
            zXGL_RenWuFanKuiNum++;
            zXGL_RenWuFanKuiQueryWrapper.lambda().like(ZXGL_RenWuFanKuiEntity::getSsxm, zXGL_RenWuFanKuiPagination.getSsxm());
        }

//        /**
//         * 数据权限 此处手动写入菜单id
//         */
//        String moduleId = "";
//        if (!userProvider.get().getIsAdministrator()) {
//            Object conditionObj = authorizeService.getCondition(zXGL_RenWuFanKuiQueryWrapper, userProvider.get(), moduleId);
//            if (ObjectUtil.isEmpty(conditionObj)) {
//                return new ArrayList<>();
//            }
//            zXGL_RenWuFanKuiQueryWrapper = (QueryWrapper<ZXGL_RenWuFanKuiEntity>) authorizeService.getCondition(zXGL_RenWuFanKuiQueryWrapper, userProvider.get(), moduleId);
//        }
        if (AllIdList.size() > 0) {
            zXGL_RenWuFanKuiQueryWrapper.lambda().in(ZXGL_RenWuFanKuiEntity::getId, AllIdList);
        }
        //排序
        if (StringUtil.isEmpty(zXGL_RenWuFanKuiPagination.getSidx())) {
            zXGL_RenWuFanKuiQueryWrapper.lambda().orderByDesc(ZXGL_RenWuFanKuiEntity::getSsxm);
        } else {
            try {
                String sidx = zXGL_RenWuFanKuiPagination.getSidx();
                ZXGL_RenWuFanKuiEntity zXGL_RenWuFanKuiEntity = new ZXGL_RenWuFanKuiEntity();
                Field declaredField = zXGL_RenWuFanKuiEntity.getClass().getDeclaredField(sidx);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                zXGL_RenWuFanKuiQueryWrapper = "asc".equals(zXGL_RenWuFanKuiPagination.getSort().toLowerCase()) ? zXGL_RenWuFanKuiQueryWrapper.orderByAsc(value) : zXGL_RenWuFanKuiQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<ZXGL_RenWuFanKuiEntity> page = new Page<>(zXGL_RenWuFanKuiPagination.getCurrentPage(), zXGL_RenWuFanKuiPagination.getPageSize());
                IPage<ZXGL_RenWuFanKuiEntity> userIPage = this.page(page, zXGL_RenWuFanKuiQueryWrapper);
                return zXGL_RenWuFanKuiPagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<ZXGL_RenWuFanKuiEntity> list = new ArrayList();
                return zXGL_RenWuFanKuiPagination.setData(list, list.size());
            }
        } else {
            return this.list(zXGL_RenWuFanKuiQueryWrapper);
        }
    }

    @Override
    public ZXGL_RenWuFanKuiEntity getInfo(String id) {
        QueryWrapper<ZXGL_RenWuFanKuiEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(ZXGL_RenWuFanKuiEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, ZXGL_RenWuFanKuiEntity entity) {
        entity.setId(id);
        return this.updateById(entity);
    }

    @Override
    public void delete(ZXGL_RenWuFanKuiEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    //子表方法
    @Override
    public List<ZXGL_RenWuFanKuiJiaoFuWuEntity> GetZXGL_RenWuFanKuiJiaoFuWuList(String id) {
        QueryWrapper<ZXGL_RenWuFanKuiJiaoFuWuEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZXGL_RenWuFanKuiJiaoFuWuEntity::getMainid, id);
        return zXGL_RenWuFanKuiJiaoFuWuService.list(queryWrapper);
    }

    @Override
    public List<ZXGL_XieBanRenWuFanKuiMXEntity> GetZXGL_XieBanRenWuFanKuiMXList(String id) {
        QueryWrapper<ZXGL_XieBanRenWuFanKuiMXEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZXGL_XieBanRenWuFanKuiMXEntity::getMainid, id);
        return zXGL_XieBanRenWuFanKuiMXService.list(queryWrapper);
    }

    //列表子表数据方法
    //子表完成反馈后修改主表反馈状态
    @Override
    public boolean updateState(String mainId) {
        ZXGL_RenWuFanKuiEntity zxglRenWuFanKuiEntity = new ZXGL_RenWuFanKuiEntity();
        zxglRenWuFanKuiEntity.setId(mainId);
        zxglRenWuFanKuiEntity.setXbrsfyqbfk("669876724938339973");
        return baseMapper.updateById(zxglRenWuFanKuiEntity) == 1 ? true : false;
    }

    @Override
    public boolean updatespzt(String taskId) {

        ZXGL_RenWuFanKuiEntity renwufankui = baseMapper.selectById(taskId);
        logger.info("renwufankui:==================>");
        if (renwufankui != null) {
            ZXGL_XiangMuFenJie_mingxibiaoEntity mingxibiao = zxglXiangMuFenJieMingxibiaoService.getById(renwufankui.getRwid());
            logger.info("renwufankui:==================>");
            if (mingxibiao != null) {
                // 目标完成值
                mingxibiao.setMbwcz(renwufankui.getMbwcz());
                // 任务进度
                mingxibiao.setRwjd(renwufankui.getDqrwjd().toString());
                // 完成情况说明
                mingxibiao.setWcqksm(renwufankui.getWcqksm());
                // ai评分、ai评价
                mingxibiao.setAipf(renwufankui.getAipf());
                mingxibiao.setAipj(renwufankui.getAipj());
                // 领导评分、领导评价
                mingxibiao.setRgpf(renwufankui.getLdpf());
                mingxibiao.setRgpj(renwufankui.getLdpj());
                logger.info("renwufankui.getDqrwjd():==================>" + renwufankui.getDqrwjd());
                logger.info("renwufankui.getDqrwjd().equals(new BigDecimal(100)):==================>" + renwufankui.getDqrwjd().equals(new BigDecimal(100)));
                if (renwufankui.getDqrwjd().equals(new BigDecimal(100))) {
                    logger.info("mingxibiao:==================>" + mingxibiao);
                    mingxibiao.setZt("667276506048763205");
                    mingxibiao.setSjwcrq(new Date());
                    logger.info("mingxibiao:==================>" + mingxibiao);
                }
                boolean update = zxglXiangMuFenJieMingxibiaoService.updateById(mingxibiao);
                logger.info("update:==================>" + update);
                renwufankui.setSpzt("1");
                // 当前流程调用为审批最后一个节点调用，所以更改是否上传知识库状态为2，通过定时器上传附件到知识库
                renwufankui.setSfsczsk(2);
                baseMapper.updateById(renwufankui);

                ZXGL_XiangMuLiXiang_MingXiEntity liXiangMingXiEntity = zxgl_xiangMuLiXiang_mingXiService.getInfo(mingxibiao.getXmid());
                if (liXiangMingXiEntity != null) {
                    BigDecimal xmjd = zxglXiangMuFenJieMingxibiaoService.selectXmjd(mingxibiao.getXmid());
                    liXiangMingXiEntity.setXmjd(xmjd);
                    zxgl_xiangMuLiXiang_mingXiService.updateById(liXiangMingXiEntity);
                }
                return true;
            }
        }
        return false;
    }

    @Override
    public List<ZXGL_XiangMuFanKui_RenWuEntity> getRenWu(String xmId) {
        QueryWrapper<ZXGL_RenWuFanKuiEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ZXGL_RenWuFanKuiEntity::getXmid, xmId).eq(ZXGL_RenWuFanKuiEntity::getSpzt, "1");
        // queryWrapper.lambda().orderByDesc(ZXGL_RenWuFanKuiEntity::getId);


        List<ZXGL_XiangMuFanKui_RenWuEntity> list = new ArrayList<>();
        List<ZXGL_RenWuFanKuiEntity> zxglRenWuFanKuiEntities = baseMapper.selectList(queryWrapper);
        if (zxglRenWuFanKuiEntities.size() > 0) {
            String[] ids = zxglRenWuFanKuiEntities.stream().map(ZXGL_RenWuFanKuiEntity::getRwid).distinct().toArray(String[]::new);
            for (String id : ids) {
                ZXGL_RenWuFanKuiEntity model = zxglRenWuFanKuiEntities.stream()
                        .filter(o -> o.getRwid() != null && o.getRwid().equals(id))
                        .sorted(Comparator.comparing(ZXGL_RenWuFanKuiEntity::getCreatorTime).reversed())
                        .findFirst().orElse(null);
                if (model != null) {
                    ZXGL_XiangMuFanKui_RenWuEntity vo = new ZXGL_XiangMuFanKui_RenWuEntity();
                    vo.setRwmc(model.getRwmc());
                    vo.setRwbh(model.getRwbh());
                    vo.setZrr(model.getFkr());
                    vo.setWcqksm(model.getWcqksm());
                    vo.setWcjd(model.getDqrwjd());
                    if (model.getRwqz() != null) {
                        vo.setRwqz(model.getRwqz());
                    }
                    vo.setJfw(model.getJfw());
                    list.add(vo);
                }
            }
        }
        //任务附件
//        if (zxglRenWuFanKuiEntities.size() > 0) {
//            ZXGL_XiangMuFanKui_RenWuEntity vo = new ZXGL_XiangMuFanKui_RenWuEntity();
//            vo.setRwmc(zxglRenWuFanKuiEntities.get(0).getRwmc());
//            vo.setRwbh(zxglRenWuFanKuiEntities.get(0).getRwbh());
//            vo.setZrr(zxglRenWuFanKuiEntities.get(0).getFkr());
//            vo.setWcqksm(zxglRenWuFanKuiEntities.get(0).getWcqksm());
//            vo.setWcjd(zxglRenWuFanKuiEntities.get(0).getDqrwjd());
//            if (zxglRenWuFanKuiEntities.get(0).getRwqz() != null) {
//                vo.setRwqz(zxglRenWuFanKuiEntities.get(0).getRwqz());
//            }
//            vo.setJfw(zxglRenWuFanKuiEntities.get(0).getJfw());
//            list.add(vo);
//        }
        return list;
    }

    @Override
    public boolean add(ZXGL_RenWuFanKuiEntity entity) {
        return baseMapper.add(entity) > 0;
    }


}
